<template>
  <!-- 新增部门的弹层 -->
  <el-dialog title="新增部门" :visible="showDialog" :before-close="handleClose">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="form" :model="formData" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width:80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
          @blur="checkManagerFn"
        >
          <el-option
            v-for="item in employee"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width:80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click.native="handleSubmit"
        >确定</el-button>
        <el-button size="small" @click.native="handleClose">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import eventBus from '@/utils/event-bus.js'
import {
  addDepartmentAPI,
  editDepartmentAPI,
  getDepartmentInfoAPI
} from '@/api/departments.js'
import { getEmployeeSimpleAPI } from '@/api/employees.js'

export default {
  props: {
    allDepartments: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验重名部门
    const checkNameFn = (rule, val, callback) => {
      const hasName = this.allDepartments
        .filter(item => item.pid === this.formData.pid) // 筛选出自己的父级部门
        .some(item => item.name === val && item.id !== this.formData.id) // 从父级部门中筛选出重名 且 不为自身
      if (hasName) return callback(new Error('该部门重名'))
      else return callback()
    }
    // 校验重复 code
    const checkCodeFn = (rule, val, callback) => {
      // 从所有部门中筛选出重名 且 不为自身
      const hasCode = this.allDepartments.some(
        item => item.code === val && this.formData.id !== item.id
      )
      if (hasCode) return callback(new Error('该 code 已存在'))
      else return callback()
    }
    return {
      showDialog: false, // 显示状态
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      }, // 表单数据
      rules: {
        code: [
          { required: true, trigger: 'blur', message: '编码不能为空' },
          { trigger: 'blur', validator: checkCodeFn },
          { message: '不得超过50个字符', max: 50, trigger: 'blur' }
        ],
        introduce: [
          { required: true, trigger: 'blur', message: '介绍不能为空' },
          { message: '不得超过300个字符', max: 300, trigger: 'blur' }
        ],
        manager: [{ required: true, trigger: 'blur', message: '不能为空' }],
        name: [
          { required: true, trigger: 'blur', message: '名称不能为空' },
          { trigger: 'blur', validator: checkNameFn },
          { message: '不得超过50个字符', max: 50, trigger: 'blur' }
        ]
      }, // 表单校验规则
      employee: [], // 员工列表
      edit: false // 新增还是修改？
    }
  },
  watch: {
    // 窗口关闭时清空数据
    showDialog(val) {
      if (!val) setTimeout(() => this.$refs.form.resetFields(), 500) // 清空数据
    }
  },
  created() {
    eventBus.$on('showDialogFn', (id, edit = false) => {
      this.showDialog = true // 打开
      this.edit = edit // 是否编辑
      if (!edit) this.formData.pid = id // 新增存pid
      if (edit) this.getDepartmentInfo(id) // 修改存id
    })
    this.getEmployeeSimple() // 下拉数据
  },
  methods: {
    // 下拉校验
    checkManagerFn() {
      setTimeout(() => this.$refs.form.validateField('manager'), 500)
    },
    // 取消提交
    handleClose() {
      this.$message.info('取消提交')
      this.showDialog = false // 关闭窗口
    },
    // 提交
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return this.$message.warning('请检查填写内容！') // 校验不通过
        // console.log(this.formData)
        this.edit
          ? await editDepartmentAPI(this.formData.id, this.formData) // 修改
          : await addDepartmentAPI(this.formData) // 新增
        // console.log(res)
        // 反馈
        this.$message.success('操作成功！')
        this.showDialog = false // 重置表单
        this.$emit('reload') // 刷新数据
      })
    },
    // 获取员工列表
    async getEmployeeSimple() {
      this.employee = await getEmployeeSimpleAPI()
    },
    // 获取详情并填充
    async getDepartmentInfo(id) {
      const res = await getDepartmentInfoAPI(id)
      // console.log(res)
      this.formData = {
        code: res.code,
        introduce: res.introduce,
        manager: res.manager,
        name: res.name,
        id
      }
    }
  }
}
</script>
